<?php

namespace app\admin\service;

use app\admin\exception\LogicException;
use app\admin\model\User as Model;
use app\admin\validate\UserValidate as Validate;

class User extends AdminService
{

	protected function init()
	{
		$this->model = new Model();
		$this->validate = new Validate();
	}

    public function toAuth(){
		#TODO:@Janmas 赋予权限没写呢
		$roleIds = $this->request->post('id');
    }

    public function create(){
	    $data = $this->request->post();
	    $file = $this->request->file('avatar');
	    if(!is_null($file)){
		    $data['avatar'] = \app\admin\model\FileManager::upload($file);
	    }else{
		    $data['avatar'] = $data['avatarfile'];
	    }
	    unset($data['avatarfile']);
	    if(empty($data['passwd'])){
		    unset($data['passwd']);
	    }else{
		    $data['passwd'] = password_hash($data['passwd'],PASSWORD_DEFAULT);
	    }
	    if(isset($data['status'])){
		    $data['status'] = 1;
	    }else{
		    $data['status'] = 0;
	    }
	    if($this->model->create($data)){
		    return $this->success('操作成功:新增');
	    }
	    throw new LogicException('操作失败：新增');
    }

    public function update( $where = [] )
    {
    	$admin = $this->model->findOrEmpty($this->request->get('id/d',0));
    	if($admin->isEmpty()){
    		throw new LogicException('管理员不存在');
	    }

	    $data = $this->request->post();
	    $file = $this->request->file('avatar');
	    if(!is_null($file)){
		    $data['avatar'] = \app\admin\model\FileManager::upload($file);
	    }else{
		    $data['avatar'] = $data['avatarfile'];
	    }
	    unset($data['avatarfile']);
		if(empty($data['passwd'])){
			unset($data['passwd']);
		}else{
			$data['passwd'] = password_hash($data['passwd'],PASSWORD_DEFAULT);
		}
		if(isset($data['status'])){
			$data['status'] = 1;
		}else{
			$data['status'] = 0;
		}
	    if($admin->data($data)->save()){
	    	return $this->success('管理员修改该');
	    }
	    throw new LogicException('修改失败');

    }


}

